<template>
  <div class="task-detail" v-loading="loading">
    <div v-if="taskInfo">
      <!-- 任务基本信息 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">基本信息</span>
          <el-tag :type="getStatusTagType(taskInfo.status)" size="medium">
            {{ getStatusText(taskInfo.status) }}
          </el-tag>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>任务名称：</label>
              <span>{{ taskInfo.taskName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>学期：</label>
              <span>{{ taskInfo.semester }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ parseTime(taskInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>创建人：</label>
              <span>{{ taskInfo.createBy || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>开始时间：</label>
              <span>{{ taskInfo.startTime ? parseTime(taskInfo.startTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>结束时间：</label>
              <span>{{ taskInfo.endTime ? parseTime(taskInfo.endTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="taskInfo.remark">
          <el-col :span="24">
            <div class="info-item">
              <label>备注：</label>
              <span>{{ taskInfo.remark }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 执行进度 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">执行进度</span>
          <span class="progress-text">{{ taskInfo.progress || 0 }}%</span>
        </div>
        
        <el-progress
          :percentage="taskInfo.progress || 0"
          :status="getProgressStatus(taskInfo.status)"
          :stroke-width="12"
          :text-inside="true"
        ></el-progress>
        
        <div v-if="taskInfo.status === 'RUNNING'" class="progress-info">
          <el-alert
            title="任务正在执行中"
            description="请耐心等待任务完成，您可以关闭此窗口，任务将在后台继续执行"
            type="info"
            show-icon
            :closable="false"
          />
        </div>
        
        <div v-if="taskInfo.status === 'FAILED' && taskInfo.errorMessage" class="error-info">
          <el-alert
            title="任务执行失败"
            :description="taskInfo.errorMessage"
            type="error"
            show-icon
            :closable="false"
          />
        </div>
      </el-card>
      
      <!-- 配置信息 -->
      <el-card class="detail-card" v-if="configData">
        <div slot="header" class="card-header">
          <span class="card-title">配置信息</span>
        </div>
        
        <el-tabs v-model="activeTab">
          <el-tab-pane label="算法配置" name="algorithm">
            <div v-if="algorithmConfig">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="config-item">
                    <label>配置名称：</label>
                    <span>{{ algorithmConfig.configName }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="config-item">
                    <label>算法类型：</label>
                    <span>{{ getAlgorithmTypeText(algorithmConfig.algorithmType) }}</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="config-item">
                    <label>种群大小：</label>
                    <span>{{ algorithmConfig.populationSize }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="config-item">
                    <label>最大迭代次数：</label>
                    <span>{{ algorithmConfig.maxGenerations }}</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="config-item">
                    <label>交叉概率：</label>
                    <span>{{ algorithmConfig.crossoverRate }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="config-item">
                    <label>变异概率：</label>
                    <span>{{ algorithmConfig.mutationRate }}</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="config-item">
                    <label>精英保留比例：</label>
                    <span>{{ algorithmConfig.eliteRate }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="config-item">
                    <label>收敛阈值：</label>
                    <span>{{ algorithmConfig.convergenceThreshold }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="约束条件" name="constraints">
            <div class="constraints-grid">
              <div class="constraint-item">
                <el-tag :type="configData.constraints.teacherConflict ? 'success' : 'info'">
                  {{ configData.constraints.teacherConflict ? '启用' : '禁用' }}
                </el-tag>
                <span>教师冲突检查</span>
              </div>
              <div class="constraint-item">
                <el-tag :type="configData.constraints.classroomConflict ? 'success' : 'info'">
                  {{ configData.constraints.classroomConflict ? '启用' : '禁用' }}
                </el-tag>
                <span>教室冲突检查</span>
              </div>
              <div class="constraint-item">
                <el-tag :type="configData.constraints.studentConflict ? 'success' : 'info'">
                  {{ configData.constraints.studentConflict ? '启用' : '禁用' }}
                </el-tag>
                <span>学生冲突检查</span>
              </div>
              <div class="constraint-item">
                <el-tag :type="configData.constraints.timePreference ? 'success' : 'info'">
                  {{ configData.constraints.timePreference ? '启用' : '禁用' }}
                </el-tag>
                <span>时间偏好优化</span>
              </div>
              <div class="constraint-item">
                <el-tag :type="configData.constraints.courseContinuity ? 'success' : 'info'">
                  {{ configData.constraints.courseContinuity ? '启用' : '禁用' }}
                </el-tag>
                <span>课程连续性</span>
              </div>
              <div class="constraint-item">
                <el-tag :type="configData.constraints.roomCapacity ? 'success' : 'info'">
                  {{ configData.constraints.roomCapacity ? '启用' : '禁用' }}
                </el-tag>
                <span>教室容量检查</span>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="优化目标" name="objectives">
            <div class="objectives-chart">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="objective-item">
                    <div class="objective-label">
                      <span>教师满意度</span>
                      <span class="objective-value">{{ configData.objectives.teacherSatisfaction }}%</span>
                    </div>
                    <el-progress
                      :percentage="configData.objectives.teacherSatisfaction"
                      :show-text="false"
                      color="#409EFF"
                    ></el-progress>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="objective-item">
                    <div class="objective-label">
                      <span>教室利用率</span>
                      <span class="objective-value">{{ configData.objectives.roomUtilization }}%</span>
                    </div>
                    <el-progress
                      :percentage="configData.objectives.roomUtilization"
                      :show-text="false"
                      color="#67C23A"
                    ></el-progress>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="objective-item">
                    <div class="objective-label">
                      <span>时间分布均匀性</span>
                      <span class="objective-value">{{ configData.objectives.timeDistribution }}%</span>
                    </div>
                    <el-progress
                      :percentage="configData.objectives.timeDistribution"
                      :show-text="false"
                      color="#E6A23C"
                    ></el-progress>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="objective-item">
                    <div class="objective-label">
                      <span>冲突最小化</span>
                      <span class="objective-value">{{ configData.objectives.conflictMinimization }}%</span>
                    </div>
                    <el-progress
                      :percentage="configData.objectives.conflictMinimization"
                      :show-text="false"
                      color="#F56C6C"
                    ></el-progress>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      
      <!-- 执行结果 -->
      <el-card class="detail-card" v-if="taskInfo.status === 'COMPLETED' && statistics">
        <div slot="header" class="card-header">
          <span class="card-title">执行结果</span>
          <el-tag type="success">执行成功</el-tag>
        </div>
        
        <el-row :gutter="20" class="statistics-row">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalCourses }}</div>
              <div class="stat-label">总课程数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.scheduledCourses }}</div>
              <div class="stat-label">已排课程</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.conflictCount }}</div>
              <div class="stat-label">冲突数量</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.overallScore }}分</div>
              <div class="stat-label">总体评分</div>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="statistics-row">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.teacherSatisfaction }}%</div>
              <div class="stat-label">教师满意度</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.roomUtilization }}%</div>
              <div class="stat-label">教室利用率</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.timeDistributionScore }}分</div>
              <div class="stat-label">时间分布得分</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.iterationCount }}</div>
              <div class="stat-label">迭代次数</div>
            </div>
          </el-col>
        </el-row>
        
        <div class="execution-time">
          <el-alert
            :title="'执行时间：' + formatExecutionTime(statistics.executionTime)"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button
          v-if="taskInfo.status === 'PENDING'"
          type="primary"
          icon="el-icon-video-play"
          @click="handleStart"
          :loading="actionLoading"
        >启动任务</el-button>
        
        <el-button
          v-if="taskInfo.status === 'RUNNING'"
          type="warning"
          icon="el-icon-video-pause"
          @click="handleStop"
          :loading="actionLoading"
        >停止任务</el-button>
        
        <el-button
          v-if="taskInfo.status === 'COMPLETED'"
          type="success"
          icon="el-icon-download"
          @click="handleDownloadResult"
        >下载结果</el-button>
        
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getScheduleTask,
  startScheduleTask,
  stopScheduleTask
} from '@/api/jwgl/scheduleTask'
import { getAlgorithmConfig } from '@/api/jwgl/algorithmConfig'
import { getStatisticsByTaskId } from '@/api/jwgl/scheduleStatistics'

export default {
  name: 'TaskDetail',
  props: {
    taskId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false,
      actionLoading: false,
      taskInfo: null,
      configData: null,
      algorithmConfig: null,
      statistics: null,
      activeTab: 'algorithm',
      refreshTimer: null
    }
  },
  created() {
    this.loadTaskDetail()
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  },
  methods: {
    /** 加载任务详情 */
    async loadTaskDetail() {
      this.loading = true
      try {
        const response = await getScheduleTask(this.taskId)
        this.taskInfo = response.data
        
        // 解析配置数据
        if (this.taskInfo.configData) {
          this.configData = JSON.parse(this.taskInfo.configData)
          
          // 加载算法配置详情
          if (this.configData.algorithmConfigId) {
            const configResponse = await getAlgorithmConfig(this.configData.algorithmConfigId)
            this.algorithmConfig = configResponse.data
          }
        }
        
        // 如果任务已完成，加载统计信息
        if (this.taskInfo.status === 'COMPLETED') {
          this.loadStatistics()
        }
        
        // 如果任务正在执行，启动定时刷新
        if (this.taskInfo.status === 'RUNNING') {
          this.startRefresh()
        }
      } catch (error) {
        this.$modal.msgError('加载任务详情失败')
      } finally {
        this.loading = false
      }
    },
    
    /** 加载统计信息 */
    async loadStatistics() {
      try {
        const response = await getStatisticsByTaskId(this.taskId)
        if (response.data && response.data.length > 0) {
          this.statistics = response.data[0]
        }
      } catch (error) {
        console.error('加载统计信息失败:', error)
      }
    },
    
    /** 启动定时刷新 */
    startRefresh() {
      this.refreshTimer = setInterval(() => {
        this.loadTaskDetail()
      }, 5000) // 每5秒刷新一次
    },
    
    /** 停止定时刷新 */
    stopRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },
    
    /** 启动任务 */
    async handleStart() {
      this.actionLoading = true
      try {
        await startScheduleTask(this.taskId)
        this.$modal.msgSuccess('任务启动成功')
        this.loadTaskDetail()
        this.startRefresh()
      } catch (error) {
        this.$modal.msgError('任务启动失败')
      } finally {
        this.actionLoading = false
      }
    },
    
    /** 停止任务 */
    async handleStop() {
      this.actionLoading = true
      try {
        await stopScheduleTask(this.taskId)
        this.$modal.msgSuccess('任务停止成功')
        this.loadTaskDetail()
        this.stopRefresh()
      } catch (error) {
        this.$modal.msgError('任务停止失败')
      } finally {
        this.actionLoading = false
      }
    },
    
    /** 下载结果 */
    handleDownloadResult() {
      // 实现结果下载逻辑
      this.$modal.msgInfo('结果下载功能开发中')
    },
    
    /** 关闭对话框 */
    handleClose() {
      this.stopRefresh()
      this.$emit('close')
    },
    
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const statusMap = {
        'PENDING': 'info',
        'RUNNING': 'warning',
        'COMPLETED': 'success',
        'FAILED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    },
    
    /** 获取状态文本 */
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待执行',
        'RUNNING': '执行中',
        'COMPLETED': '已完成',
        'FAILED': '已失败',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || '未知'
    },
    
    /** 获取进度条状态 */
    getProgressStatus(status) {
      if (status === 'COMPLETED') return 'success'
      if (status === 'FAILED') return 'exception'
      return null
    },
    
    /** 获取算法类型文本 */
    getAlgorithmTypeText(type) {
      const typeMap = {
        'GENETIC': '遗传算法',
        'SIMULATED_ANNEALING': '模拟退火',
        'PARTICLE_SWARM': '粒子群优化',
        'TABU_SEARCH': '禁忌搜索'
      }
      return typeMap[type] || type
    },
    
    /** 格式化执行时间 */
    formatExecutionTime(milliseconds) {
      if (!milliseconds) return '0秒'
      
      const seconds = Math.floor(milliseconds / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)
      
      if (hours > 0) {
        return `${hours}小时${minutes % 60}分钟${seconds % 60}秒`
      } else if (minutes > 0) {
        return `${minutes}分钟${seconds % 60}秒`
      } else {
        return `${seconds}秒`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.task-detail {
  .detail-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .card-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
      
      .progress-text {
        font-size: 14px;
        font-weight: 500;
        color: #409EFF;
      }
    }
    
    .info-item {
      margin-bottom: 12px;
      
      label {
        font-weight: 500;
        color: #606266;
        margin-right: 8px;
        min-width: 80px;
        display: inline-block;
      }
      
      span {
        color: #303133;
      }
    }
    
    .config-item {
      margin-bottom: 12px;
      
      label {
        font-weight: 500;
        color: #606266;
        margin-right: 8px;
        min-width: 100px;
        display: inline-block;
      }
      
      span {
        color: #303133;
      }
    }
  }
  
  .progress-info,
  .error-info {
    margin-top: 16px;
  }
  
  .constraints-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    
    .constraint-item {
      display: flex;
      align-items: center;
      
      .el-tag {
        margin-right: 8px;
        min-width: 40px;
        text-align: center;
      }
      
      span {
        color: #303133;
      }
    }
  }
  
  .objectives-chart {
    .objective-item {
      margin-bottom: 20px;
      
      .objective-label {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        span {
          color: #303133;
          font-weight: 500;
        }
        
        .objective-value {
          color: #409EFF;
          font-weight: 600;
        }
      }
    }
  }
  
  .statistics-row {
    margin-bottom: 20px;
    
    .stat-item {
      text-align: center;
      padding: 16px;
      background-color: #f8f9fa;
      border-radius: 6px;
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 13px;
        color: #909399;
      }
    }
  }
  
  .execution-time {
    margin-top: 16px;
  }
  
  .action-buttons {
    margin-top: 30px;
    text-align: right;
    border-top: 1px solid #e4e7ed;
    padding-top: 20px;
    
    .el-button {
      margin-left: 10px;
    }
  }
}
</style>